#!/usr/bin/env bash

set -e

HERE="`dirname $0`"
VERSION=$(sed -nre "s#[[:space:]]*version[^0-9]+([0-9.]+)#\1#p" $HERE/../.scalafmt.conf)
COURSIER="$HERE/.coursier"
SCALAFMT="$HERE/.scalafmt-$VERSION"
CHECK_MODIFIED_ONLY=${CHECK_MODIFIED_ONLY:-false}

if [ ! -f $COURSIER ]; then
  curl -L -o $COURSIER https://git.io/coursier-cli
  chmod +x $COURSIER
fi

if [ ! -f $SCALAFMT ]; then
  $COURSIER bootstrap org.scalameta:scalafmt-cli_2.13:$VERSION -r sonatype:snapshots --main org.scalafmt.cli.Cli -o $SCALAFMT
  chmod +x $SCALAFMT
fi

if [[ "$CHECK_MODIFIED_ONLY" == "1" ]]; then
  git diff --name-only main | \
    grep -E '.*\.scala$' |
    xargs "$SCALAFMT"
else 
  $SCALAFMT "$@"
fi
